#include "StdAfx.h"
#include "DIResourceManager.h"
#include "../Engine/DAnimation.h"
#include "../DGlobals.h"
#include "../Engine/DImage.h"
#include <fstream>

DIResourceManager::DIResourceManager(void)
{
}

DIResourceManager::~DIResourceManager(void)
{
}

bool DIResourceManager::loadAnimation(const std::string& strAnimName, bool bIsBackground /*= false*/)
{
    std::string fullPath = DGlobals::instance().graphicsPath() + strAnimName + ".anm";
    std::ifstream in(fullPath.c_str(), std::ifstream::in);

    std::string imagesFolder = fullPath.substr(0, fullPath.find_last_of("/"));

    if(in.is_open())
    {
        boost::shared_ptr<DAnimation> anim(new DAnimation());
		int numFrames = 0;
        while(!in.eof())
        {
            char strImage[256];
            in.getline(strImage, 256);

			if(strlen(strImage) != 0)
			{
				std::string imagePath = imagesFolder + "/" + strImage;
				boost::shared_ptr<DImage> image = loadImage(imagePath, bIsBackground);

				if(image)
				{
					m_images.push_back(image);
					anim->addFrame(image);
					numFrames++;
					anim->setDimensions(image->width(), image->height());
				}
				else
				{
					return false;
				}
			}
        }

		anim->setSingleFrame( (numFrames == 1) ? true : false);
        m_anims[strAnimName] = anim;
        return true;
    }

    return false;
}

boost::shared_ptr<DAnimation> DIResourceManager::animation(const std::string& strAnimName)
{
    boost::shared_ptr<DAnimation> deepCopy;

    AnimMap::iterator anim = m_anims.find(strAnimName);

    if(anim != m_anims.end())
    {
        deepCopy = boost::shared_ptr<DAnimation>(new DAnimation());

        // NOTE: images are shallow copies
        *deepCopy = *(anim->second);
    }

    return deepCopy;
}